//
//  HMEmoticonModel.swift
//  表情键盘
//
//  Created by iOS on 16/9/28.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

/// 一个表情模型
class HMEmoticonModel: NSObject, NSCoding {
    /// 图片所在的文件夹名称
    var id: String?
    
    /// 表情名称
    var chs: String?
    
    /// 图片名称
    var png: String? {
        didSet {
            // 图片的完整路径 = bundlePath + 文件夹的名称 + 图片名称
            if let id = id, let png = png {
                fullPngPath = bundlePath + "/" + id + "/" + png
            }
        }
    }
    
    /// 图片的完整路径
    var fullPngPath: String?
    
    /// emoji的16进制字符串
    var code: String? {
        didSet {
            
            // 扫描器
            let scanner = Scanner(string: code!)
            
            // result: UnsafeMutablePointer<UInt32>?: 不安全的可变的 UInt32 类型的指针
            var result: UInt32 = 0
            scanner.scanHexInt32(&result)
            
//            print("result: \(result)")
            
            emoji = String(Character(UnicodeScalar(result)!))
        }
    }
    
    var emoji: String?
    
    init(id: String, dict: [String: String]) {
        self.id = id
        super.init()
        
        self.setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
    /// 打印
    override var description: String {
        get {
            let keys = ["chs", "png", "code"]
            return "\n \t\t 表情模型: \(dictionaryWithValues(forKeys: keys))"
        }
    }
    
    // MARK: - 归档和解档
    required init?(coder aDecoder: NSCoder) {
        id = aDecoder.decodeObject(forKey: "id") as? String
        chs = aDecoder.decodeObject(forKey: "chs") as? String
        
        // 在init方法里面赋值是不会触发didSet
        png = aDecoder.decodeObject(forKey: "png") as? String
        // 因为每次运行程序的路径会变化,记录图片的完整路径后,下次启动找不到图片了.
//        fullPngPath = aDecoder.decodeObject(forKey: "fullPngPath") as? String
        code = aDecoder.decodeObject(forKey: "code") as? String
        emoji = aDecoder.decodeObject(forKey: "emoji") as? String
        
        // 图片的完整路径 = bundlePath + 文件夹的名称 + 图片名称
        if let id = id, let png = png {
            fullPngPath = bundlePath + "/" + id + "/" + png
        }
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(chs, forKey: "chs")
        aCoder.encode(png, forKey: "png")
        aCoder.encode(fullPngPath, forKey: "fullPngPath")
        aCoder.encode(code, forKey: "code")
        aCoder.encode(emoji, forKey: "emoji")
    }
}
